package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.dto.IndentDto;
import com.xxx.dto.OrderDto;
import com.xxx.pojo.Indent;
import com.xxx.pojo.OrderLine;
import com.xxx.pojo.ShoppingCart;
import com.xxx.service.IndentService;
import com.xxx.service.OrderLineService;
import com.xxx.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/indent")
@Slf4j
public class IndentController {


    @Autowired
    private IndentService indentService;

    @Autowired
    private OrderLineService orderLineService;

    @Autowired
    private ShoppingCartService shoppingCartService;
    @PostMapping("/save")
    public Result saveIndent(@RequestBody IndentDto indentDto){

        Indent indent = new Indent();
        BeanUtils.copyProperties(indentDto,indent,Indent.class);

        log.info("indent:{}",indent);

        indentService.save(indent);


        //将dto进行分解转换
        List<OrderLine> orderList = indentDto.getCartList().stream().map(shoppingCart -> {
            OrderLine orderLine = new OrderLine();
            BeanUtils.copyProperties(shoppingCart, orderLine);
            orderLine.setIndentId(indent.getId());
            orderLine.setPrice(shoppingCart.getPrice().multiply(new BigDecimal(shoppingCart.getNum())));
            return orderLine;

        }).collect(Collectors.toList());
        log.info("orderList:{}",orderList);

        boolean b = orderLineService.saveBatch(orderList);

        if (b){
            boolean remove = shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, indent.getOrderUser()));
        }

        return b ? new Result(Code.SAVE_OK) : new Result(Code.SAVE_ERR);
    }

    @GetMapping("/list")
    public Result getOrderList(Long id){
        List<Indent> list = indentService.list(new LambdaQueryWrapper<Indent>().eq(Indent::getOrderUser, id));

        //dto赋值
        List<OrderDto> dtoList = list.stream().map(indent -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(indent, orderDto);

            List<OrderLine> lineList = orderLineService.list(new LambdaQueryWrapper<OrderLine>().eq(OrderLine::getIndentId, indent.getId()));
            orderDto.setOrderList(lineList);

            int sum = lineList.stream().mapToInt(OrderLine::getNum).sum();
            orderDto.setSumNum(sum);
            log.info("orderDto:{}", orderDto);
            return orderDto;
        }).collect(Collectors.toList());




        return new Result(dtoList,Code.GET_OK);
    }

}
